package com.xc.ksxt.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xc.common.object.Constant;
import com.xc.common.object.UEditorObject;
import com.xc.common.tool.Helper;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@RestController
@RequestMapping({ "/uploadImage" })
public class UploadImageController {
    @Value("${env.filedir}")
    private String filedir;
    @Value("${env.imageurl}")
    private String imageurl;
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @RequestMapping({ "" })
    @Transactional
    @CrossOrigin
    public JSONObject upload1(HttpServletRequest request, HttpServletResponse response) {
        CommonsMultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        UEditorObject respo = new UEditorObject();
        JSONObject res = new JSONObject();
        String action = request.getParameter("action");
        if(action==null||action.equals("config")){
            respo.setImageActionName("upload");
            List<String> imageFileTypes = new ArrayList<>();
            imageFileTypes.add(".jpg");
            imageFileTypes.add(".bmp");
            imageFileTypes.add(".png");

            respo.setImageAllowFiles(imageFileTypes);
            res = JSON.parseObject(JSON.toJSONString(respo));
        }else if(action.equals("upload")){
            res = upload(request,response);

        }


        return res;
    }
    public JSONObject upload(HttpServletRequest request, HttpServletResponse response) {
        CommonsMultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        JSONObject respo = new JSONObject();
        respo.put("state","SUCCESS");

        String fileName = "";
        MultipartFile file = null;
        if(resolver.isMultipart(request)){
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
            Iterator iterator = multiRequest.getFileNames();
            while(iterator.hasNext()){
                file = multiRequest.getFile((String) iterator.next());
                if(file!=null){
                    break;
                }
            }
            fileName = file.getOriginalFilename();
            String sufix = Helper.getSuffix(fileName).toLowerCase();
            if(!sufix.equals("png")&&!sufix.equals("jpg")){
                respo.put("state","上传文件类型不允许");
            }else{
                String rela = "zdtest/" + LocalDate.now().getYear() + "/";
                String tempFilePath = filedir+"/" + rela;
                File tempFileDir = new File(tempFilePath);
                String newname = "";
                String absolutePath = "";
                try {
                    if(!tempFileDir.exists()) {
                        FileUtils.forceMkdir(tempFileDir);
                    }
                    newname = Helper.getSnowId() + "." + sufix;
                    absolutePath = tempFilePath + newname;
                    file.transferTo(new File(absolutePath));
                    respo.put("url",rela + newname);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return respo;
    }

}
